﻿using System.Collections.Generic;
using UnityEngine;

namespace Snake.Misc
{
    public static class Utils
    {
        private static readonly Collider2D[] Results = new Collider2D[256];

        public static int OverlapEllipseNonAlloc(Vector2 point, float radiusX, float radiusY,
            out List<Collider2D> results,
            int layerMask = -1)
        {
            var radius = Mathf.Max(radiusX, radiusY);
            results = new List<Collider2D>();
            var len = 0;
            if (layerMask < 0)
            {
                len = Physics2D.OverlapCircleNonAlloc(point, radius, Results);
            }
            else
            {
                len = Physics2D.OverlapCircleNonAlloc(point, radius, Results, layerMask);
            }

            for (var i = 0; i < len; i++)
            {
                var p = Results[i].transform.position;
                if (!IsPointInsideEllipse(point, radiusX, radiusY, p))
                {
                    continue;
                }

                results.Add(Results[i]);
            }

            return results.Count;
        }

        // 检查点是否在椭圆内部
        public static bool IsPointInsideEllipse(Vector2 center, float radiusX, float radiusY, Vector2 point)
        {
            var normalizedX = (point.x - center.x) / radiusX;
            var normalizedY = (point.y - center.y) / radiusY;

            return normalizedX * normalizedX + normalizedY * normalizedY < 1f;
        }
    }
}